<template>
  <div>
    <!-- 面包屑导航 -->
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>商品管理</el-breadcrumb-item>
        <el-breadcrumb-item>分类参数</el-breadcrumb-item>
      </el-breadcrumb>
    <!-- / 面包屑导航 -->
    <!-- 卡片视图 -->
    <el-card>
      <el-alert
        title="只允许为第三级分类设置相关参数!"
        type="warning"
        :closable='false'
        show-icon>
      </el-alert>
      <div style="margin:15px 0">
        选择商品分类：
        <el-cascader
          v-model="cacadervalue"
          :options="goodsCates"
          :props="cascaderProps"
          @change="cascaderHandleChange">
        </el-cascader>
        <!-- 标签页 -->
        <el-tabs v-model="activeName" @tab-click="tabsHandleClick">
          <!-- 动态参数 -->
          <el-tab-pane label="动态参数" name="many">
            <el-button @click="addParamsDialogVisible = true" :disabled="isDisabled" size="mini" type="primary">添加参数</el-button>
            <!-- 表格 -->
            <el-table border stripe :data="manyTableTada">
              <el-table-column type='expand'>
                <template slot-scope="scope">
                  <el-tag @close='removeTag(scope.row), index' closable v-for="(item, index) in scope.row.attr_vals" :key='index'>{{item}}</el-tag>
                  <!-- 动态显示输入框 -->
                  <el-input
                    class="input-new-tag"
                    v-if="scope.row.inputVisible"
                    v-model="scope.row.inputValue"
                    ref="saveTagInput"
                    size="small"
                    @keyup.enter.native="handleInputConfirm(scope.row)"
                    @blur="handleInputConfirm(scope.row)">
                  </el-input>
                  <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
                </template>
              </el-table-column>
              <el-table-column type='index' label="#"></el-table-column>
              <el-table-column label='参数名称' prop="attr_name"></el-table-column>
              <el-table-column label="操作">
                <template slot-scope="scope">
                  <el-button @click='showEditDialog(scope.row)' type="primary" size="mini" icon="el-icon-edit">修改</el-button>
                  <el-button @click='showDelete(scope.row)' type='danger' size="mini" icon="el-icon-delete">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
          <!-- 静态属性 -->
          <el-tab-pane label="静态属性" name="only">
            <el-button @click="addParamsDialogVisible = true" :disabled="isDisabled" size="mini" type="primary">添加属性</el-button>
            <!-- 表格 -->
            <el-table border stripe :data="onlyTableTada">
              <el-table-column type='expand'>
                <template slot-scope="scope">
                  <el-tag @close='removeTag(scope.row), index' closable v-for="(item, index) in scope.row.attr_vals" :key='index'>{{item}}</el-tag>
                  <!-- 动态显示输入框 -->
                  <el-input
                    class="input-new-tag"
                    v-if="scope.row.inputVisible"
                    v-model="scope.row.inputValue"
                    ref="saveTagInput"
                    size="small"
                    @keyup.enter.native="handleInputConfirm(scope.row)"
                    @blur="handleInputConfirm(scope.row)">
                  </el-input>
                  <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
                </template>
              </el-table-column>
              <el-table-column type='index' label="#"></el-table-column>
              <el-table-column label='参数名称' prop="attr_name"></el-table-column>
              <el-table-column label="操作">
                <template slot-scope="scope">
                  <el-button @click='showEditDialog(scope.row)' type="primary" size="mini" icon="el-icon-edit">修改</el-button>
                  <el-button @click='showDelete(scope.row)' type='danger' size="mini" icon="el-icon-delete">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
        </el-tabs>
        <!-- 添加 -->
        <el-dialog
          @close='closeAddParams'
          :title="'添加' + addParamsText"
          :visible.sync="addParamsDialogVisible"
          width="50%">
          <el-form ref="addParamsFormRef" :rules="addParamsRules" :model="addParamsForm" label-width="80px">
            <el-form-item prop='attr_name' :label='addParamsText'>
              <el-input v-model="addParamsForm.attr_name"></el-input>
            </el-form-item>
          </el-form>
          <span slot="footer" class="dialog-footer">
            <el-button @click="addParamsDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="submitAddParams">确 定</el-button>
          </span>
        </el-dialog>
        <!-- 编辑-->
        <el-dialog
        @close='subEditParams'
          :title="'添加' + addParamsText"
          :visible.sync="editParamsDialogVisible"
          width="50%">
          <el-form ref="editParamsFormRef" :rules="addParamsRules" :model="editParamsForm" label-width="80px">
            <el-form-item prop='attr_name' :label='addParamsText'>
              <el-input v-model="editParamsForm.attr_name"></el-input>
            </el-form-item>
          </el-form>
          <span slot="footer" class="dialog-footer">
            <el-button @click="editParamsDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="submitEditParams">确 定</el-button>
          </span>
        </el-dialog>
      </div>
    </el-card>
    <!-- / 卡片视图 -->
  </div>
</template>

<script>
export default {
  data () {
    return {
      // 商品分类
      goodsCates: [],
      // 双向绑定
      cacadervalue: [],
      cascaderProps: {
        expandTrigger: 'hover',
        label: 'cat_name',
        value: 'cat_id'
      },
      activeName: 'many',
      // 接收动态参数
      manyTableTada: [],
      // 接收静态属性
      onlyTableTada: [],
      addParamsDialogVisible: false,
      addParamsForm: {
        attr_name: ''
      },
      addParamsRules: {
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' },
          { min: 2, max: 8, message: '长度在 2 到 8 个字符', trigger: 'blur' }
        ]
      },
      // 修改
      editParamsDialogVisible: false,
      editParamsForm: {
        attr_name: ''
      },
      inputVisible: false,
      inputValue: ''
    }
  },

  created () {
    this.getGoodsCate()
  },
  computed: {
    // 计算按钮是否被禁用
    isDisabled () {
      return this.cacadervalue.length !== 3
    },
    // 计算三级分类id
    cateId () {
      if (this.cacadervalue.length !== 3) {
        return null
      }
      return this.cacadervalue[2]
    },
    addParamsText () {
      return this.activeName === 'only' ? '静态属性' : '动态参数'
    }
  },
  methods: {
    // 获取商品分类数据
    async getGoodsCate () {
      const { data: res } = await this.$axios.get('categories')
      if (res.meta.status !== 200) return this.$message.error('获取失败!')
      this.goodsCates = res.data
    },
    // 获取参数
    async getParams () {
      if (this.cacadervalue.length !== 3) {
        this.cacadervalue = []
        this.manyTableTada = []
        this.onlyTableTada = []
        return
      }
      const { data: res } = await this.$axios.get('categories/' + this.cateId + '/attributes', {
        params: {
          sel: this.activeName
        }
      })
      if (res.meta.status !== 200) return this.$message.error('获取失败!')
      res.data.forEach(item => {
        item.attr_vals = item.attr_vals === '' ? [] : item.attr_vals.split(' ')
        item.inputVisible = false
        item.inputValue = ''
      })
      if (this.activeName === 'only') {
        this.onlyTableTada = res.data
      } else {
        this.manyTableTada = res.data
      }
    },
    async cascaderHandleChange () {
      this.getParams()
    },
    tabsHandleClick () {
      this.getParams()
    },
    submitAddParams () {
      this.$refs.addParamsFormRef.validate(async flag => {
        if (!flag) return
        const { data: res } = await this.$axios.post('categories/' + this.cateId + '/attributes', {
          attr_name: this.addParamsForm.attr_name,
          attr_sel: this.activeName
        })
        if (res.meta.status !== 201) return this.$message.error('创建失败!')
        this.$message.success('创建成功!')
        this.addParamsDialogVisible = false
        this.getParams()
      })
    },
    closeAddParams () {
      this.$refs.addParamsFormRef.resetFields()
    },
    showEditDialog (row) {
      this.editParamsDialogVisible = true
      this.editParamsForm = { ...row }
    },
    submitEditParams () {
      this.$refs.editParamsFormRef.validate(async flag => {
        if (!flag) return
        const { data: res } = await this.$axios.put(`categories/${this.cateId}/attributes/${this.editParamsForm.attr_id}`, {
          attr_name: this.editParamsForm.attr_name,
          attr_sel: this.activeName
        })
        if (res.meta.status !== 200) return this.$message.error('更新失败!')
        this.$message.success('更新成功!')
        this.editParamsDialogVisible = false
        this.getParams()
      })
    },
    subEditParams () {
      this.$refs.editParamsFormRef.resetFields()
    },
    showDelete (row) {
      this.$confirm('此操作将永久删除该文件, 是否继续？', '提示', {
        distinguishCancelAndClose: true,
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }).then(async () => {
        const { data: res } = await this.$axios.delete(`categories/${this.cateId}/attributes/${row.attr_id}`)
        if (res.meta.status !== 200) return this.$message.error('删除失败!')
        this.$message.success('删除成功!')
        this.getParams()
      }).catch(action => {
        this.$message('已取消删除!')
      })
    },
    async handleInputConfirm (row) {
      if (row.inputValue.trim() === '') {
        row.inputVisible = false
        row.inputValue = ''
        return
      }
      row.attr_vals.push(row.inputValue)
      // 发送请求同步后台
      const { data: res } = await this.$axios.put(`categories/${this.cateId}/attributes/${row.attr_id}`, {
        attr_name: row.attr_name,
        attr_sel: this.activeName,
        attr_vals: row.attr_vals.join(' ')
      })
      if (res.meta.status !== 200) return this.$message.error('更新失败!')
      this.$message.success('更新成功!')
      row.inputVisible = false
      row.inputValue = ''
    },
    showInput (row) {
      row.inputVisible = true
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    async removeTag (row, index) {
      row.attr_vals.splice(index, 1)
      const { data: res } = await this.$axios.put(`categories/${this.cateId}/attributes/${row.attr_id}`, {
        attr_name: row.attr_name,
        attr_sel: this.activeName,
        attr_vals: row.attr_vals.join(' ')
      })
      if (res.meta.status !== 200) return this.$message.error('更新失败!')
      this.$message.success('更新成功!')
    }
  }
}
</script>

<style scoped lang='less'>
  .el-tag {
    margin: 7px;
  }
  .input-new-tag {
    width: 120px;
  }
</style>
